﻿using System; using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KeanuMvc.Reference;
using HIS.Utils;
using System.Reflection;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HISModels.Entities;
using System.Net;
using System.Configuration;
using HIS.Utils.Securities;
using HISModels.ViewModel;

namespace HIS.Controllers.Admins {

    public class ActionGroup : HIS.Controllers.AppBaseController {

        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private HISModels.Entities.SysActionGroup sysActionGroup = null;
        private HISModels.Entities.SysAction sysAction = null;
        #endregion

        #region Action Group

        public ActionGroup() {
            Data.Add("Pagetitle", " Modules");
            Data.Add("Notification", strNotification);
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public override void Index() {
            try {
                RenderFile("admins\\actions\\actiongroup.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public void TableList() {
            try {
                ///--------- Sample post to rest and get record as paging-------------/// 
                ///Create paging object///
                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sSearch = HttpContext.Current.Request["sSearch"];
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                //
                ///Set Rest Url///
                //string strUri = Data["servicerooturl"] + "sys/actiongroups/paging/?format=json";
                string strUri = Global.ServiceUriDictionary["actgroupspaging"] + Global.ServiceUriDictionary["requestformat"];
                ///Post paging object to rest as json string///
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                ///Read response value///
                string strJson = stringReader.ReadToEnd();
                ///----------Consistenly clean up all object------------///
                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public void EditActionGroup() {
            StringReader stringReader = null;
            /// Get id record from querystring
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                /// Throw to list if something goes wrong
                GoToUrl("actiongroup/"); return;
            }

            try {
                ///Set Rest Url///
                string strUri = Global.ServiceUriDictionary["actgroups"] + id + Global.ServiceUriDictionary["requestformat"];
                ///Get Rest///
                stringReader = base.RestService.GetJson(strUri);
                ///Deserialize json response to object///
                sysActionGroup = JsonConvert.DeserializeObject<SysActionGroup>(stringReader.ReadToEnd());
                ///Set variable for rendering on view HTML///
                Data.Add("sysActionGroup", sysActionGroup);
                Data.Add("IsCreate", "false");
                Data["Notification"] = strNotification;
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Actions\\editactiongroup.html");
                stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public void DeleteActionGroup() {
            StringReader stringReader = null;
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("actiongroup/");
                return;
            }

            try {
                sysActionGroup = new HISModels.Entities.SysActionGroup();
                string strUri = Global.ServiceUriDictionary["actgroups"] + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                var a = JsonConvert.DeserializeObject<SysActionGroup>(stringReader.ReadToEnd());
                
                if (strNotification == string.Empty) strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                
                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";

            } catch (Exception ex) {
                strNotification = "{\"strNotification\": \"" + ex.Message + "\"}";
            } finally {
                HttpContext.Current.Response.Redirect(Data["rooturl"] + "admins/actiongroup/");
                HttpContext.Current.Response.Write(strNotification);
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public void CreateActionGroup() {
            try {
                Data["Pagetitle"] += " :: Add Module";
                sysActionGroup = new HISModels.Entities.SysActionGroup() { DescValue = string.Empty };
                Data.Add("sysActionGroup", sysActionGroup);
                Data.Add("IsCreate", "true");
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Actions\\editactiongroup.html");
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public void SaveActionGroup() {
            StringReader stringReader = null;
            string strUri = string.Empty;
            try {
                sysActionGroup = new SysActionGroup(); Utils.Helper.SetNullToEmptyString(sysActionGroup);
                if (HttpContext.Current.Request["IsCreate"] != "true") {
                    int id = 0;
                    try {
                        id = Convert.ToInt32(HttpContext.Current.Request["id"]);
                    } catch { }
                    strUri = Global.ServiceUriDictionary["actgroups"] + id + Global.ServiceUriDictionary["requestformat"];
                    stringReader = base.RestService.GetJson(strUri);
                    sysActionGroup = JsonConvert.DeserializeObject<SysActionGroup>(stringReader.ReadToEnd());
                }

                sysActionGroup.PostHandler<HISModels.Entities.SysActionGroup>();

                strUri = Global.ServiceUriDictionary["actgroups"] + Global.ServiceUriDictionary["requestformat"];

                if (HttpContext.Current.Request["IsCreate"] == "true") {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(sysActionGroup));
                } else {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(sysActionGroup));
                }

                string temp = stringReader.ReadToEnd();
                sysActionGroup = JsonConvert.DeserializeObject<SysActionGroup>(temp);

                if (sysActionGroup != null) {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                } else {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }


                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                
            } catch (Exception ex) {
                strNotification = "{\"strNotification\": \"" + ex.Message + "\"}";
            } finally {
                HttpContext.Current.Response.Write(strNotification);
                base.RestService.Dispose();
            }
        }

        #endregion

        #region Action

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public void SettingAction() {
            int groupid = 0;
            try {
                groupid = Convert.ToInt32(HttpContext.Current.Request["groupid"]);
            } catch {
                GoToUrl("actiongroup/");
                return;
            }
            try {
                string strUri = Global.ServiceUriDictionary["actgroups"] + groupid + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.GetJson(strUri);
                HISModels.Entities.SysActionGroup sysActionGroup = JsonConvert.DeserializeObject<SysActionGroup>(stringReader.ReadToEnd());

                Data["Pagetitle"] = "Module  :: Module Action (" + sysActionGroup.DescValue + ")";
                Data.Add("ActionGroupID", sysActionGroup.Id.NullSafeToString());
                HttpContext.Current.Session["ActionGroupID"] = sysActionGroup.Id.NullSafeToString();
                RenderFile("admins\\actions\\viewaction.html");

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public void TableListAction() {

            try {

                string search = "key=" + HttpContext.Current.Request["sSearch"].NullSafeToString() + ";id=" + HttpContext.Current.Session["ActionGroupID"].NullSafeToString();

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sSearch = search;
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);

                string strUri = Global.ServiceUriDictionary["actpaging"] + Global.ServiceUriDictionary["requestformat"];
                ///Post paging object to rest as json string///
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                ///Read response value///
                string strJson = stringReader.ReadToEnd();
                ///----------Consistenly clean up all object------------///
                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        public string DropDownAction(string Selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string strUri = Global.ServiceUriDictionary["actgroups"] + Global.ServiceUriDictionary["requestformat"];


            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<SysActionGroup> listAction = JsonConvert.DeserializeObject<List<SysActionGroup>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                foreach (SysActionGroup item in listAction) activeArr.Add(new object[] { item.Id, item.DescValue });

                strResult = KeanuMvc.Reference.Html.DropDown("Idd", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public void EditActionSetting() {
            StringReader stringReader = null;
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["Id"]);
            } catch { GoToUrl("actiongroup/"); return;}

            try {

                string strUri = Global.ServiceUriDictionary["action"] + id + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);
                sysAction = JsonConvert.DeserializeObject<SysAction>(stringReader.ReadToEnd());
                Data.Add("sysAction", sysAction);
                Data.Add("IsCreate", "false");
                Data["Notification"] = strNotification;
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Actions\\editaction.html");
                stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public void CreateActionSetting() {
            try {
                Data["Pagetitle"] += " :: Add Module";
                sysAction = new HISModels.Entities.SysAction() { DescValue = string.Empty };
                Data.Add("ddactions", DropDownAction(sysAction.ActionGroupId.NullSafeToString()));
                sysAction.ActionGroupId = Convert.ToInt32(HttpContext.Current.Request["groupid"]);
                Data.Add("sysAction", sysAction);
                Data.Add("IsCreate", "true");
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Actions\\editaction.html");
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public void SaveAction() {
            StringReader stringReader = null;
            string strUri = string.Empty;
            try {
                sysAction = new SysAction(); Utils.Helper.SetNullToEmptyString(sysAction);
                if (HttpContext.Current.Request["IsCreate"] != "true") {
                    int id = 0;
                    try {
                        id = Convert.ToInt32(HttpContext.Current.Request["IdAction"]);
                    } catch { }
                    strUri = Global.ServiceUriDictionary["action"] + id + Global.ServiceUriDictionary["requestformat"];
                    ///Get Rest///
                    stringReader = base.RestService.GetJson(strUri);
                    sysAction = JsonConvert.DeserializeObject<SysAction>(stringReader.ReadToEnd());
                }

                sysAction.PostHandler<HISModels.Entities.SysAction>();
                sysAction.DescValue = sysAction.DescValue.ReplaceSpecialChar("-").ToLower();
                sysAction.ActionGroupId = Convert.ToInt32(HttpContext.Current.Request["ActionGroupId"]);
                strUri = Global.ServiceUriDictionary["action"] + Global.ServiceUriDictionary["requestformat"];

                if (HttpContext.Current.Request["IsCreate"] == "true") {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(sysAction));
                } else {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(sysAction));

                }
                string temp = stringReader.ReadToEnd();


                sysAction = JsonConvert.DeserializeObject<SysAction>(temp);

                if (sysAction != null) {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                } else {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }


                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                HttpContext.Current.Response.Write(strNotification);

            } catch (Exception ex) {
                //strNotification = "{\"strNotification\": \"" + ex.Message + "\"}";
                HttpContext.Current.Response.Write(ex.Message);
            } finally {

                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-module")]
        public void DeleteActionSetting() {
            int id = 0;
            try {
                id = int.Parse(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("actiongroup/");
                return;
            }
            try {
                sysAction = new HISModels.Entities.SysAction();
                string strUri = Global.ServiceUriDictionary["action"] + Global.ServiceUriDictionary["requestformat"];

                StringReader strReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                var a = JsonConvert.DeserializeObject<SysAction>(strReader.ReadToEnd());

                if (string.IsNullOrEmpty(strNotification)) strNotification = Helper.InformationMessage(strNotification);
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Actions\\viewaction.html");
                base.RestService.Dispose();
            }
        }

        #endregion

    }
}



